package com.computer.network.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.computer.network.mapper.*;
import com.computer.network.po.*;
import com.computer.network.service.AuthorityService;
import com.computer.network.util.MyHashMap;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;


@Transactional(rollbackFor = Exception.class)
@Service
public class AuthorityServiceImpl implements AuthorityService {
    @Resource
    SysUserMapper sysUserMapper;
    @Resource
    SysUserRoleRelationMapper sysUserRoleRelationMapper;
    @Resource
    SysRoleRangeMapper sysRoleRangeMapper;
    @Resource
    SysRangeMapper sysRangeMapper;
    @Resource
    RedisTemplate<String, HashMap> redisTemplate;
    @Resource
    SysRoleMapper sysRoleMapper;

    @Override
    public void addRole(SysRole sysRole) {
        sysRoleMapper.insert(sysRole);
    }

    @Override
    public void removeRole(SysRole sysRole) {
        //删除权限表
        sysRoleMapper.deleteById(sysRole.getId());
        //删除角色权限表
        QueryWrapper<SysRoleRange> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("role_id", sysRole.getId());
        sysRoleRangeMapper.delete(queryWrapper1);
        //删除角色用户表
        QueryWrapper<SysUserRoleRelation> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("role_id", sysRole.getId());
        sysUserRoleRelationMapper.delete(queryWrapper2);
    }

    @Override
    public void updateRole(SysRole sysRole) {
        //更改当前权限id下的权限属性
        sysRoleMapper.updateById(sysRole);
    }

    @Override
    public List<String> selectRole(SysRole sysRole) {
        List<String> urlsList = new ArrayList<>();
        long roleId = sysRole.getId();
        //通过角色id查询对应权限id
        QueryWrapper<SysRoleRange> sysRoleRangeQueryWrapper = new QueryWrapper<>();
        sysRoleRangeQueryWrapper.eq("role_id", roleId);
        List<SysRoleRange> sysRoleRanges = sysRoleRangeMapper.selectList(sysRoleRangeQueryWrapper);
        //取出权限id
        List<Long> rangeIdList = sysRoleRanges.stream().map(SysRoleRange::getRangeId).collect(Collectors.toList());
        for (Long rangeId : rangeIdList) {
            //具体请求url拼接
            SysRange sysRange = sysRangeMapper.selectById(rangeId);
            //不能直接设置为null
            StringBuilder s = new StringBuilder("");
            if (sysRange.getIsMenu() == 1) {
                String url = sysRange.getUrl();
                s.append(url);
                s.append("/*/*");
            } else if (sysRange.getIsModular() == 1) {
                long superior = sysRange.getSuperior();
                SysRange sysRange1 = sysRangeMapper.selectById(superior);
                String url1 = sysRange1.getUrl();
                String url2 = sysRange.getUrl();
                s.append(url1);
                s.append(url2);
                s.append("/*");
            } else {
                String url1 = sysRange.getUrl();
                long superior1 = sysRange.getSuperior();
                SysRange sysRange1 = sysRangeMapper.selectById(superior1);
                String url2 = sysRange1.getUrl();
                long superior2 = sysRange1.getSuperior();
                SysRange sysRange2 = sysRangeMapper.selectById(superior2);
                String url3 = sysRange2.getUrl();
                s.append(url3);
                s.append(url2);
                s.append(url1);
            }
            urlsList.add(String.valueOf(s));
        }
        return urlsList;
    }

    @Override
    public boolean addUser(SysUser sysUser) {
        int insert = sysUserMapper.insert(sysUser);
        if (insert > 0) {
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean removeUser(SysUser sysUser) {
        //获取用户的id值
        long id = sysUser.getId();
        //通过id值删除用户角色关联表中对应的数据
        QueryWrapper<SysUserRoleRelation> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",id);
        //删除关联表的数据
        int delete = sysUserRoleRelationMapper.delete(wrapper);
        //删除用户表的数据
        int i = sysUserMapper.deleteById(id);
        if (delete > 0 && i> 0){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean updateUser(SysUser sysUser) {
        int i = sysUserMapper.updateById(sysUser);
        if (i > 0){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public List<String> selectUser(SysUser sysUser) {
        List<String> urlsList = new ArrayList<>();
        QueryWrapper<SysUserRoleRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", sysUser.getId());
        List<SysUserRoleRelation> sysUserRoleRelations = sysUserRoleRelationMapper.selectList(queryWrapper);
        //遍历角色
        for (SysUserRoleRelation sysUserRoleRelation : sysUserRoleRelations) {
            long roleId = sysUserRoleRelation.getRoleId();
            //通过角色id查询对应权限id
            QueryWrapper<SysRoleRange> sysRoleRangeQueryWrapper = new QueryWrapper<>();
            sysRoleRangeQueryWrapper.eq("role_id", roleId);
            List<SysRoleRange> sysRoleRanges = sysRoleRangeMapper.selectList(sysRoleRangeQueryWrapper);
            //取出权限id
            List<Long> rangeIdList = sysRoleRanges.stream().map(SysRoleRange::getRangeId).collect(Collectors.toList());
            for (Long rangeId : rangeIdList) {
                //具体请求url拼接
                SysRange sysRange = sysRangeMapper.selectById(rangeId);
                //不能直接设置为null
                StringBuilder s = new StringBuilder("");
                if (sysRange.getIsMenu() == 1) {
                    String url = sysRange.getUrl();
                    s.append(url);
                    s.append("/*/*");
                } else if (sysRange.getIsModular() == 1) {
                    long superior = sysRange.getSuperior();
                    SysRange sysRange1 = sysRangeMapper.selectById(superior);
                    String url1 = sysRange1.getUrl();
                    String url2 = sysRange.getUrl();
                    s.append(url1);
                    s.append(url2);
                    s.append("/*");
                } else {
                    String url1 = sysRange.getUrl();
                    long superior1 = sysRange.getSuperior();
                    SysRange sysRange1 = sysRangeMapper.selectById(superior1);
                    String url2 = sysRange1.getUrl();
                    long superior2 = sysRange1.getSuperior();
                    SysRange sysRange2 = sysRangeMapper.selectById(superior2);
                    String url3 = sysRange2.getUrl();
                    s.append(url3);
                    s.append(url2);
                    s.append(url1);
                }
                urlsList.add(String.valueOf(s));
            }
        }
        return urlsList;
    }

    @Override
    public boolean addRange(SysRange sysRange) {
        int insert = sysRangeMapper.insert(sysRange);
        if (insert > 0) {
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean removeRange(SysRange sysRange) {
        //获取权限id
        long rangeId = sysRange.getRangeId();
        //通过权限id来查询是否为主模块。
        boolean childFlag = isChild(rangeId);
        QueryWrapper<SysRange> wrapper = new QueryWrapper<>();
        //childFlag为true有子节点 ，childFlag为false没有子节点
        if (childFlag) {
            //有子节点先删除子节点，在删除主节点。
            wrapper.eq("superior",rangeId);
            //删除子节点的数据
            int delete = sysRangeMapper.delete(wrapper);
            //删除主节点的数据
            int i = sysRangeMapper.deleteById(rangeId);
            return delete > 0 && i > 0 ;
        }else {
            //没有子节点，直接删除主节点
            int i = sysRangeMapper.deleteById(rangeId);
            return i > 0;
        }
    }

    @Override
    public List<SysRange> selectRange() {
        //获得权限列表
        List<SysRange> sysRanges = sysRangeMapper.selectList(null);
        sysRanges.forEach(item -> {
            long rangeId = item.getRangeId();
            boolean flag = isChild(rangeId);
            if (flag){
                item.setHasChild(true);
            }
        });
        return sysRanges;
    }

    @Override
    public void redisTable(String K) {
        //K：权限 V：对应角色id集合（存在一个地址被多个角色id所持有）
        MyHashMap hashMap1 = new MyHashMap();
        //查询数据库中所有角色
        List<SysUserRoleRelation> sysUserRoleRelations = sysUserRoleRelationMapper.selectList(null);
        //遍历角色
        for (SysUserRoleRelation sysUserRoleRelation : sysUserRoleRelations) {
            long roleId = sysUserRoleRelation.getRoleId();
            //通过角色id查询对应权限id
            QueryWrapper<SysRoleRange> sysRoleRangeQueryWrapper = new QueryWrapper<>();
            sysRoleRangeQueryWrapper.eq("role_id", roleId);
            List<SysRoleRange> sysRoleRanges = sysRoleRangeMapper.selectList(sysRoleRangeQueryWrapper);
            //取出权限id
            List<Long> rangeIdList = sysRoleRanges.stream().map(SysRoleRange::getRangeId).collect(Collectors.toList());
            for (Long rangeId : rangeIdList) {
                StringBuffer s = new StringBuffer("");
                //具体请求url拼接
                SysRange sysRange = sysRangeMapper.selectById(rangeId);
                String rangeName = sysRange.getRangeName();
                //不能直接设置为null
                if (sysRange.getIsMenu() == 1) {
                    String url = sysRange.getUrl();
                    s.append(url);
                    s.append("/*/*");
                } else if (sysRange.getIsModular() == 1) {
                    long superior = sysRange.getSuperior();
                    SysRange sysRange1 = sysRangeMapper.selectById(superior);
                    String url1 = sysRange1.getUrl();
                    String url2 = sysRange.getUrl();
                    s.append(url1);
                    s.append(url2);
                    s.append("/*");
                } else {
                    String url1 = sysRange.getUrl();
                    long superior1 = sysRange.getSuperior();
                    SysRange sysRange1 = sysRangeMapper.selectById(superior1);
                    String url2 = sysRange1.getUrl();
                    long superior2 = sysRange1.getSuperior();
                    SysRange sysRange2 = sysRangeMapper.selectById(superior2);
                    String url3 = sysRange2.getUrl();
                    s.append(url3);
                    s.append(url2);
                    s.append(url1);
                }
                hashMap1.put(String.valueOf(s), String.valueOf(roleId));
            }
        }
        redisTemplate.opsForValue().setIfAbsent(K, hashMap1);
    }

    /**
     * 判断是否有子节点
     * @param id
     * @return
     */
    private boolean isChild(Long id){
        QueryWrapper<SysRange> wrapper = new QueryWrapper<>();
        wrapper.eq("superior",id);
        Integer count = sysRangeMapper.selectCount(wrapper);
        // count > 0 为true 否则为false
        return count > 0;
    }
}
